var mongoose = require('mongoose');
var express = require('express');
const router = express.Router();

const bodyParser     = require('body-parser');
var cors = require('cors');

var UserModel = require('../../db/schemas/user.js')
// var UserModel = mongoose.model('User', UserSchema);

router.use(bodyParser.urlencoded({ extended: false }))
router.post('/api/reg', (req, res)=>{
    if(req.body.email && 
            req.body.username && 
            req.body.password && 
            req.body.passwordConf)
        {

        var userData = {
            email: req.body.email,
            username: req.body.username,
            password: req.body.password,
            passwordConf: req.body.passwordConf
        };

        UserModel.create(userData, function(err, user){
            if(err) {
                res.send(err);
                console.error(err);
            }
            else{
                return res.send('created!')
            }
        })
    }
    else{
        res.send({code: 403, req: req.body})
    }
});

router.post('/api/login', (req, res)=>{
    UserModel.authenticate(req.body.email, req.body.password, function (error, user) {
        if (error || !user) {
            var err = new Error('Wrong email or password.');
            err.status = 401;
            // return next(err);
            res.send("err");
        } else {
            req.session.userId = user._id;
            return res.redirect('/index.html');
        }
    });
})

module.exports = router;